(function(){
	if (!window.jQuery)
	{
		alert('jQuery not included!');
		return false;
	}

	var _treeMenu = function(e, baseUrl){
		this.ele = e;
		this.url = baseUrl;
		this.init();
	}

	_treeMenu.prototype.init = function(){
		var that = this;
		$.ajax({
			url: that.url,
			type: 'post',
			dataType: 'text',
			timeout: 1000,
			error: function(){
				//error
				alert('Serve Error! Main Menu could not be loaded! Try Refresh!');
			},
			success: function(xml){
				//append to ele
				ul = $(xml).css('display', 'none').appendTo(that.ele);
				$('li', that.ele).addClass('package-close');
				$(that.ele).bind('click', that.childUpdate());
				ul.slideDown();
			}
		});
	}

	_treeMenu.prototype.childUpdate = function(){
		var that = this;

		return function(e){
			var evt = e || window.event;
			var ele = e.target || e.srcElement;

			//assert ele as a element and has a li parentNode
			if (ele.nodeName != 'A' || ele.parentNode.nodeName != 'LI')
			{
				return false;
			}

			uls = $('ul', ele.parentNode);

			//if display none remove and ajax update
			if (uls.length && uls[0].style.display != 'none')
			{
				uls.slideUp();
				$(ele.parentNode).removeClass('package-open').removeClass('package-refresh').addClass('package-close');
				return false;
			}
			else if(uls.length){
				uls.remove();
			}

			$(ele.parentNode).removeClass('package-open').removeClass('package-close').addClass('package-refresh');
			
			$.ajax({
				url: that.url,
				type: 'post',
				dataType: 'text',
				timeout: 1000,
				data: {'ele': ele.rel},
				error: function(){
					//parse error
					alert('Could not load sub menu, request may be failed!');
					//reset state
					$(ele.parentNode).removeClass('package-refresh').addClass('package-close');
				},
				success: function(xml){
					//append to ele
					if (xml == '')
					{
						//empty submenu
						$(ele.parentNode).removeClass('package-refresh').addClass('package-close');
						return false;
					}

					//return xml parsing
					ul = $(xml).css('display', 'none').appendTo(ele.parentNode);
					$('li', ele.parentNode).addClass('package-close');
					ul.slideDown();
					$(ele.parentNode).removeClass('package-refresh').addClass('package-open');
				}
			});

			return false;
		}
	}

	window.treeMenu = _treeMenu;
})();